package com.itany.service.impl;

import com.itany.entity.*;
import com.itany.mapper.*;
import com.itany.service.ServerService;
import com.itany.utils.OssClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ServerServiceImpl implements ServerService {
    @Autowired
    private ServerInfoMapper mapper;
    @Autowired
    private ServerTypeMapper serverTypeMapper;
    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private ServerAreaMapper serverAreaMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private AnnexMapper annexMapper;
    @Autowired
    private NoticeMapper noticeMapper;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Map<String, Object>> queryByParams(String servername, Integer flag, String companyid) {
        List<ServerInfo> list = mapper.selectByParams(servername,flag,companyid);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if(!list.isEmpty()) {
            for (ServerInfo serverInfo : list) {
                Map<String, Object> u = new HashMap<>();
                u.put("id",serverInfo.getId());
                u.put("servername",serverInfo.getServername());
                u.put("linkman",serverInfo.getLinkman());
                u.put("phone",serverInfo.getPhone());
                u.put("commpanyname",serverInfo.getCompanyName());
                u.put("commpanytype",serverInfo.getCompanyType());
                u.put("commpanylevel",serverInfo.getLevel());
                u.put("username",serverInfo.getUsername());
                u.put("createdate",serverInfo.getCreatedate());
                u.put("flag",serverInfo.getFlag());
                mapList.add(u);
            }
            return mapList;
        }else{
            return null;
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public void modifyStatus(Integer id,Integer managerUserId) {
        ServerInfo server = mapper.selectByPrimaryKey(id);
        if(server.getFlag() == 1){
            server.setFlag(0);
            Notice notice = new Notice();
            notice.setTitle("管理员操作");
            notice.setInfo("发布的服务被禁用!");
            notice.setManageruserid(managerUserId);
            notice.setUserid(server.getUserid());
            notice.setFlag(1);
            notice.setCreatedate(new Date());
            noticeMapper.insertSelective(notice);
        }else{
            server.setFlag(1);
            Notice notice = new Notice();
            notice.setTitle("管理员操作");
            notice.setInfo("发布的服务被成功启用!");
            notice.setManageruserid(managerUserId);
            notice.setUserid(server.getUserid());
            notice.setFlag(1);
            notice.setCreatedate(new Date());
            noticeMapper.insertSelective(notice);
        }
        mapper.updateByPrimaryKeySelective(server);
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Map<String,Object> findById(Integer id) {
        ServerInfo serverInfo = mapper.selectById(id);
        if(serverInfo != null){
            Map<String,Object> map = new HashMap<>();
            map.put("servername",serverInfo.getServername());
            map.put("linkman",serverInfo.getLinkman());
            map.put("phone",serverInfo.getPhone());
            map.put("commpanyname",serverInfo.getCompanyName());
            map.put("commpanytype",serverInfo.getCompanyType());
            map.put("commpanylevel",serverInfo.getLevel());
            map.put("createdate",serverInfo.getCreatedate());
            String str1 = "";
            String str2 = "";
            List<String> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            ServerTypeExample serverTypeExample = new ServerTypeExample();
            serverTypeExample.or().andServeridEqualTo(id);
            List<ServerType> serverTypeList = serverTypeMapper.selectByExample(serverTypeExample);
            if(!serverTypeList.isEmpty()){
                for(ServerType serverType : serverTypeList){
                    Type type = typeMapper.selectByPrimaryKey(serverType.getTypeid());
                    list1.add(type.getName());
                }
                str1 = String.join(",",list1);
            }
            ServerAreaExample serverAreaExample = new ServerAreaExample();
            serverAreaExample.or().andServeridEqualTo(id);
            List<ServerArea> serverAreaList = serverAreaMapper.selectByExample(serverAreaExample);
            if(!serverTypeList.isEmpty()){
                for(ServerArea serverArea : serverAreaList){
                    Area area = areaMapper.selectByPrimaryKey(serverArea.getAreaid());
                    list2.add(area.getName());
                }
                str2 = String.join(",",list2);
            }
            map.put("servertype",str1);
            map.put("serverarea",str2);
            map.put("flag",serverInfo.getFlag());
            map.put("info",serverInfo.getInfo());
            List<String> imageUrls = new ArrayList<>();
            AnnexExample annexExample1 = new AnnexExample();
            annexExample1.or().andKeyidEqualTo(id).andTypeEqualTo("1").andTabletypeEqualTo(3);
            List<Annex> annexList1 = annexMapper.selectByExample(annexExample1);
            if(!annexList1.isEmpty()){
                for(Annex annex : annexList1){
                    imageUrls.add(annex.getPath()+annex.getFilename());
                }
            }
            map.put("imageUrls",imageUrls);
            return map;
        }else{
            return null;
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Map<String, Object> findInfo(Integer id) {
        ServerInfo serverInfo = mapper.selectById(id);
        if(serverInfo != null){
            Map<String,Object> map = new HashMap<>();
            map.put("servername",serverInfo.getServername());
            map.put("linkman",serverInfo.getLinkman());
            map.put("phone",serverInfo.getPhone());
            map.put("commpanyname",serverInfo.getCompanyName());
            map.put("commpanytype",serverInfo.getCompanyType());
            map.put("commpanylevel",serverInfo.getLevel());
            List<Type> types = typeMapper.selectSecondParam(serverInfo.getCompanyType());
            List<Map<String,Object>> mapList1 = new ArrayList<>();
            List<Integer> values1 = new ArrayList<>();
            if(!types.isEmpty()){
                for(Type type : types){
                    Map<String,Object> objectMap = new HashMap<>();
                    objectMap.put("id",type.getId());
                    objectMap.put("text",type.getName());
                    mapList1.add(objectMap);
                }
            }
            map.put("serverTypeOptions",mapList1);
            ServerTypeExample serverTypeExample = new ServerTypeExample();
            serverTypeExample.or().andServeridEqualTo(id);
            List<ServerType> serverTypeList = serverTypeMapper.selectByExample(serverTypeExample);
            if(!serverTypeList.isEmpty()){
                for(ServerType serverType : serverTypeList){
                    values1.add(serverType.getTypeid());
                }
            }
            map.put("selectedServerTypeValues",values1);
            List<Area> areas = areaMapper.selectSecondParam();
            List<Map<String,Object>> mapList2 = new ArrayList<>();
            List<Integer> values2 = new ArrayList<>();
            if(!areas.isEmpty()){
                for(Area area : areas){
                    Map<String,Object> objectMap = new HashMap<>();
                    objectMap.put("id",area.getId());
                    objectMap.put("text",area.getName());
                    mapList2.add(objectMap);
                }
            }
            map.put("serverAreaOptions",mapList2);
            ServerAreaExample serverAreaExample = new ServerAreaExample();
            serverAreaExample.or().andServeridEqualTo(id);
            List<ServerArea> serverAreaList = serverAreaMapper.selectByExample(serverAreaExample);
            if(!serverAreaList.isEmpty()){
                for(ServerArea serverArea : serverAreaList){
                    values2.add(serverArea.getAreaid());
                }
            }
            map.put("selectedServerAreaValues",values2);
            map.put("info",serverInfo.getInfo());
            List<String> imageUrls = new ArrayList<>();
            AnnexExample annexExample1 = new AnnexExample();
            annexExample1.or().andKeyidEqualTo(id).andTypeEqualTo("1").andTabletypeEqualTo(3);
            List<Annex> annexList1 = annexMapper.selectByExample(annexExample1);
            if(!annexList1.isEmpty()){
                for(Annex annex : annexList1){
                    imageUrls.add(annex.getPath()+annex.getFilename());
                }
            }
            map.put("imageUrls",imageUrls);
            return map;
        }else{
            return null;
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public void modifyInfo(Integer id, String name, Integer[] types, Integer[] areas, String info, MultipartFile[] imgs, String existingImages) {
        ServerInfo serverInfo = new ServerInfo();
        serverInfo.setId(id);
        serverInfo.setServername(name);
        serverInfo.setInfo(info);
        mapper.updateByPrimaryKeySelective(serverInfo);
        ServerTypeExample serverTypeExample = new ServerTypeExample();
        serverTypeExample.or().andServeridEqualTo(id);
        serverTypeMapper.deleteByExample(serverTypeExample);
        for(Integer type : types){
            ServerType serverType = new ServerType();
            serverType.setServerid(id);
            serverType.setTypeid(type);
            serverTypeMapper.insertSelective(serverType);
        }
        ServerAreaExample serverAreaExample = new ServerAreaExample();
        serverAreaExample.or().andServeridEqualTo(id);
        serverAreaMapper.deleteByExample(serverAreaExample);
        for(Integer area : areas){
            ServerArea serverArea = new ServerArea();
            serverArea.setServerid(id);;
            serverArea.setAreaid(area);
            serverAreaMapper.insertSelective(serverArea);
        }
            AnnexExample annexExample = new AnnexExample();
            annexExample.or().andTypeEqualTo("1").andKeyidEqualTo(id).andTabletypeEqualTo(3);
            List<Annex> annexList = annexMapper.selectByExample(annexExample);
            annexMapper.deleteByExample(annexExample);
            String[] exists = existingImages.split(",");
            for (String exist : exists){
                try {
                    if(exist != null && !exist.isEmpty()){
                        MultipartFile file = OssClientUtil.convert(exist);
                        Map<String,Object> map = OssClientUtil.uploadImage("service/",file);
                        String path = map.get("path").toString() + "/service/";
                        String filename = map.get("filename").toString();
                        Annex annex = new Annex();
                        annex.setPath(path);
                        annex.setFilename(filename);
                        annex.setType("1");
                        annex.setKeyid(id);
                        annex.setTabletype(3);
                        annexMapper.insertSelective(annex);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(!annexList.isEmpty()) {
                for(Annex annex : annexList){
                    String key = "service/" + annex.getFilename();
                    OssClientUtil.deleteImage(key);
                }
            }
        if (imgs != null) {
            for(MultipartFile file : imgs){
                try {
                    Map<String,Object> map = OssClientUtil.uploadImage("service/",file);
                    String path = map.get("path").toString() + "/service/";
                    String filename = map.get("filename").toString();
                    Annex annex = new Annex();
                    annex.setPath(path);
                    annex.setFilename(filename);
                    annex.setType("1");
                    annex.setKeyid(id);
                    annex.setTabletype(3);
                    annexMapper.insertSelective(annex);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
